import 'package:f_enjoy_plus_community/utils/http.dart';
import 'package:f_enjoy_plus_community/utils/toast.dart';
import 'package:f_enjoy_plus_community/utils/token.dart';
import 'package:flutter/material.dart';

import '../../utils/eventbus.dart';
import '../house/house_list.dart';

class MinePage extends StatefulWidget {
  MinePage({super.key, required this.index});

  int index = 0;

  @override
  State<MinePage> createState() => _MinePageState();
}

class _MinePageState extends State<MinePage> {
  // 菜单数据
  final List menuList = [
    {"title": "我的房屋", "icon": "assets/images/house_profile_icon@2x.png"},
    {"title": "我的报修", "icon": "assets/images/repair_profile_icon@2x.png"},
    {"title": "访客记录", "icon": "assets/images/visitor_profile_icon@2x.png"},
  ];

  Map userInfo = {"id": "", "avatar": null, "nickName": null};

  //当父 widget 重新构建，并且传递给当前 state 的 widget 配置（即 widget 的属性）有变化时，
  // didUpdateWidget 方法会被触发。
  @override
  void didUpdateWidget(covariant MinePage oldWidget) {
    super.didUpdateWidget(oldWidget);
    print("收到的参数是${widget.index}");
    if (widget.index == 1) {
      //TODO:获取个人中心的数据
      getUserInfo();
    }
  }

  @override
  void initState() {
    super.initState();
    eventBus.on<RefreshMineEvent>().listen((event) {
      print('登录收到刷新事件');
      getUserInfo();
    });
  }

  void getUserInfo() async {
    //TODO:获取个人中心数据
    try {
      final res = await http.get('/userInfo');
      if (res['code'] != 10000) {
        ToastUtil.showError('网络请求与错误');
        return;
      }

      print(res['data']);

      setState(() {
        userInfo = res['data'];
      });
    } catch (e) {
      print(e);
      ToastUtil.showError('网络请求与错误');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color.fromARGB(200, 85, 145, 175),
      appBar: AppBar(
        title: const Text('我的', style: TextStyle(color: Colors.white)),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: ListView(
        children: [
          // 个人信息
          Container(
            padding: const EdgeInsets.all(10),
            child: GestureDetector(
              onTap: () {
                Navigator.pushNamed(context, '/profile', arguments: userInfo);
              },
              child: Row(
                children: [
                  Row(
                    children: [
                      ClipRRect(
                        borderRadius: BorderRadius.circular(50.0),
                        child: userInfo['avatar'] == null
                            ? Image.asset(
                                'assets/images/avatar_1.jpg',
                                width: 50,
                                height: 50,
                              )
                            : Image.network(
                                userInfo['avatar'],
                                width: 50,
                                height: 50,
                              ),
                      ),
                      const SizedBox(width: 10),
                      Text(
                        userInfo['nickName'] ?? '未登录',
                        style: const TextStyle(
                          fontSize: 16,
                          color: Colors.white,
                        ),
                      ),
                    ],
                  ),
                  const Spacer(),
                  const Row(
                    children: [
                      Text('去完善信息', style: TextStyle(color: Colors.white)),

                      Icon(
                        Icons.arrow_forward_ios,
                        color: Colors.white,
                        size: 13,
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
          Container(
            padding: const EdgeInsets.all(15),
            margin: const EdgeInsets.only(
              top: 20,
              left: 10,
              right: 10,
              bottom: 20,
            ),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(10),
            ),
            child: Column(
              children: menuList.map((item) {
                return GestureDetector(
                  onTap: () {
                    if (item['title'] == '我的房屋') {
                      Navigator.pushNamed(context, '/house_list');
                    }

                  },
                  child: SizedBox(
                    height: 50,
                    child: Row(
                      children: [
                        Row(
                          children: [
                            Image.asset(item['icon'], width: 20, height: 20),
                            const SizedBox(width: 10),
                            Text(
                              item['title'],
                              style: const TextStyle(fontSize: 16),
                            ),
                          ],
                        ),
                        const Spacer(),
                        const Icon(
                          Icons.arrow_forward_ios,
                          size: 12,
                          color: Colors.grey,
                        ),
                      ],
                    ),
                  ),
                );
              }).toList(),
            ),
          ),
          ElevatedButton(
            onPressed: () async {
              await TokenManager().saveToken('token12345');
            },
            child: Text('存Token任意'),
          ),
          SizedBox(height: 10),
          ElevatedButton(
            onPressed: () async {
              await TokenManager().saveToken('token12345');
              getHost();
            },
            child: Text('修改token再请求'),
          ),
          SizedBox(height: 10),
          ElevatedButton(
            onPressed: () async {
              await TokenManager().removeToken();
            },
            child: Text('删Token'),
          ),
        ],
      ),
    );
  }

  void getHost() async {
    final res = await http.get('/room');
    print(res);
  }
}
